package org.activequant.util.matlab;

import java.io.BufferedWriter;
import java.io.ObjectInputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

import org.apache.log4j.Logger;

/**
 * 
 * Matlab Client counterpart.<br>
 * Holds the following associated variables:
 * <ul>
 * <li>host(String)</li>
 * <li>port(int)</li>
 * </ul>
 * <b>History:</b><br>
 *  - [8.4.2008] Created (ustaudinger)<br>
 *
 *  @author ustaudinger
 */
public class MatlabClient {
	/**
	 * private String host = "aqaba";
	 */
	private String host = "aqaba";
	/**
	 * private int port = 10001;
	 */
	private int port = 10001;
	
	private final static Logger log = Logger.getLogger(MatlabClient.class);
	/**
	 * constructs a MatlabClient and sends a "1" through a Socket using its associated
	 * host(String) and port(int) defaults (host="aqaba" and port=10001)
	 * @throws Exception
	 */
	public MatlabClient() throws Exception {
		eval("1");
	}
	/**
	 * constructs a MatlabClient using the given host(String) and port(int) to set its associated host(String) and port(int).
	 * It also sends a "1" through a Socket to that host(String) and port(int).
	 * @param host
	 * @param port
	 * @throws Exception
	 */
	public MatlabClient(String host, int port) throws Exception {
		this.host = host; 
		this.port = port; 
		eval("1");
	}
	
	/**
	 * method to send something to matlab and receive the reply. <br/>
	 * Sends the given line(String) through a Socket to the associated host(String) and port(int)
	 * and then reads and returns the response Object.
	 * @param line
	 * @return
	 * @throws Exception
	 */
	public Object eval(String line) throws Exception {
		
		
		log.debug("Connecting socket.. ");
		Socket s = new Socket(host, port);
		
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        log.debug("Sending line "+line);
		bw.write(line);
    	bw.newLine();
    	bw.flush();
        
    	
      	ObjectInputStream oin = new ObjectInputStream(s.getInputStream());
      	log.debug("About to read object ...");
    	Object o = oin.readObject();
    	log.debug(o);
    	
    	s.close();
    	
        return o;
	}
	
}
